<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<script src="lib/easeljs-0.7.1.min.js"></script>
	<script src="lib/tweenjs-0.5.1.min.js"></script>
</head>
<body onload="init()">
	<canvas id="mycanvas" width="700px" height="500px" style="border:1px solid black;"></canvas>
</body>
</html>
<style>
	body{text-align: center;}
</style>

<script>
	var stage;
	var shapes=[];
	var slots=[];
	var score=0;
	function init(){
		stage = new createjs.Stage("mycanvas");
		buildShapes();

		createjs.Ticker.setFPS(60);
		createjs.Ticker.addEventListener('tick',function(){
			stage.update()
		})
	}

	function buildShapes(){
		var colors = ["blue","yellow","green","pink"]
		var i,shape,slot;
		for (var i = 0; i < 4; i++){
			slot = new createjs.Shape();
			slot.graphics.beginStroke(colors[i]);
			slot.graphics.beginFill("#ffffff");
			slot.graphics.drawRect(0,0,100,100);
			slot.key = i;
			slot.y = 50;
			slot.x = (166*i)+50;
			stage.addChild(slot);
			slots.push(slot)

		}

		var r;
		for (var i = 0; i < 4; i++){
			shape = new createjs.Shape();
			shape.graphics.beginFill(colors[i]);
			shape.graphics.drawRect(0,0,100,100);
			shape.key = i;
			shapes.push(shape)
			r = Math.floor(Math.random()*shapes.length)
			shape = shapes[r];
			shape.homeY = 250;
			shape.homeX = (166*i)+50;
			shape.x = shape.homeX;
			shape.y = shape.homeY;
			shape.addEventListener('mousedown',drawDrag)
			stage.addChild(shape)
			shapes.splice(r,1)
		} 

	}

	function drawDrag(e){
		var shape = e.target
		var slot = slots[shape.key]
		stage.setChildIndex(shape,stage.getNumChildren()-1);
		stage.addEventListener("stagemousemove",function(e){
			shape.x = e.stageX;
			shape.y = e.stageY;
		})

		stage.addEventListener("stagemouseup",function(e){
			stage.removeAllEventListeners();
			var pt = slot.globalToLocal(stage.mouseX,stage.mouseY);
			if(slot.hitTest(pt.x,pt.y)){
				shape.removeEventListener("mousedown",drawDrag);
				score++;
				createjs.Tween.get(shape).to({x:slot.x,y:slot.y},200,createjs.Ease.quadOut).call(function(){
					if(score==4){
						alert("恭喜你，拼对了！（智商没问题一般都能被恭喜）")
					}
				})
			}else{
				createjs.Tween.get(shape).to({x:shape.homeX,y:shape.homeY},200,createjs.Ease.quadOut)
			}
		})

	}



</script>